package cn.topevery.garden.dal.dao.impl;

import cn.topevery.garden.dal.dao.QuestionnaireDao;
import cn.topevery.garden.dal.logic.QuestionnaireAnswerLogic;
import cn.topevery.garden.dal.logic.QuestionnaireDetailLogic;
import cn.topevery.garden.dal.logic.WxScoreLogic;
import cn.topevery.garden.entity.po.Questionnaire;
import cn.topevery.garden.entity.po.QuestionnaireAnswer;
import cn.topevery.garden.entity.po.QuestionnaireDetail;
import cn.topevery.garden.entity.po.WxScore;
import cn.topevery.garden.entity.query.QuestionnaireQuery;
import cn.topevery.garden.entity.vo.QuestionnaireVO;
import cn.topevery.garden.framework.base.BaseDaoImpl;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.basis.runtime.UserRuntime;
import hw.topevery.framework.db.CommandType;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.db.entity.SqlQueryMate;
import hw.topevery.framework.db.entity.SqlUpdateMate;
import hw.topevery.framework.db.enums.ScriptConditionEnum;
import hw.topevery.framework.entity.DbCsp;
import hw.topevery.framework.entity.KeyValue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 问卷调查主表
 *
 * @author code-generate
 * @date 2022-01-05
 */
@Repository
public class QuestionnaireDaoImpl extends BaseDaoImpl<Questionnaire> implements QuestionnaireDao {
    @Autowired
    private QuestionnaireDetailLogic questionnaireDetailLogic;
    @Autowired
    private QuestionnaireAnswerLogic questionnaireAnswerLogic;
    @Autowired
    private WxScoreLogic wxScoreLogic;
    @Override
    public <P extends DbCsp> List<Questionnaire> getSearch(P para) {
        return null;
    }

    

    @Override
    public DataPager<QuestionnaireVO> listPage(QuestionnaireQuery query) {
        String table = "t_questionnaire tq";

        String columns = "tq.*";

        int pageIndex = query.pageIndex - 1;
        int pageSize = query.pageSize;

        SqlQueryMate sqlQueryMate = new SqlQueryMate(table).setColumns(columns).setOrderBy("tq.c_db_update_date desc");
        sqlQueryMate
                .where(true, "tq.c_db_status", ScriptConditionEnum.Eq, 0)
                .where(StringUtils.isNotBlank(query.getBeginDate()), "tq.c_date", ScriptConditionEnum.GreaterThanEq, query.getBeginDate())
                .where(StringUtils.isNotBlank(query.getEndDate()), "tq.c_date", ScriptConditionEnum.LessThanEq, query.getEndDate());

        return getDataPager(sqlQueryMate, pageSize, pageIndex, QuestionnaireVO.class);
    }

    @Override
    public Questionnaire getEntityByColumn(String key,String value){
        KeyValue<String> map=new KeyValue<>();
        map.key=key;
        map.value=value;
        return getEntityByColumnEqValue(map);
    }

    @Override
    public void commitQuestionnaire(Questionnaire questionnaire, Integer userId) {
        SysUser user = UserRuntime.getSysUser();
        questionnaire.setDbUpdateId(userId);
        questionnaire.setDbUpdateDate(LocalDateTime.now());
        if (questionnaire.getId() == null) {
            questionnaire.setDbStatus(false);
            questionnaire.setUserId(userId);
            questionnaire.setStatus(1);
            insert(user.userId, questionnaire);
        } else {
            update(user.userId, questionnaire);
        }
        //题目信息
        for (QuestionnaireDetail detail : questionnaire.getDetailList()) {
            detail.setMainId(questionnaire.getId());
            questionnaireDetailLogic.commitQuestionnaireDetail(detail, userId);
        }
    }

    @Transactional
    @Override
    public void deleteQuestionnaireById(Integer id, Integer userId) {
        List<QuestionnaireDetail> detailList = questionnaireDetailLogic.getQuestionnaireDetailList(id);
        for (QuestionnaireDetail questionnaireDetail : detailList) {
            questionnaireDetailLogic.deleteQuestionnaireDetailById(questionnaireDetail.getId(), userId);
        }
        SqlUpdateMate sqlUpdateMate = new SqlUpdateMate("t_questionnaire");
        sqlUpdateMate.setColumnValue(true, "c_db_status", 1)
                .setColumnValue(true, "c_db_update_date", LocalDateTime.now())
                .setColumnValue(true, "c_db_update_id", userId)
                .where(true, "c_id", ScriptConditionEnum.Eq, id);
        run(sqlUpdateMate.getSql(), CommandType.Text, dbCommand -> {
            sqlUpdateMate.getParameters().forEach(dbCommand::addParameter);
            dbCommand.executeNonQuery();
        });
    }

    @Override
    public Questionnaire getQuestionnaireById(Integer id) {
        SqlQueryMate sqlQueryMate = new SqlQueryMate("t_questionnaire").setColumns("*");
        sqlQueryMate.where(true, "c_db_status", ScriptConditionEnum.Eq, 0)
                .where(id!=null, "c_id", ScriptConditionEnum.Eq, id);
        Questionnaire questionnaire = selectOne(sqlQueryMate, Questionnaire.class);
        if (questionnaire != null) {
            questionnaire.setDetailList(questionnaireDetailLogic.getQuestionnaireDetailList(id));
        }
        return questionnaire;
    }

    @Override
    public void changeStatus(Integer id, Integer status, Integer userId) {
        SqlUpdateMate sqlUpdateMate = new SqlUpdateMate("t_questionnaire");
        sqlUpdateMate.setColumnValue(true, "c_db_status", status + 1)
                .setColumnValue(true, "c_db_update_date", LocalDateTime.now())
                .setColumnValue(true, "c_db_update_id", userId)
                .where(true, "c_id", ScriptConditionEnum.Eq, id);
        run(sqlUpdateMate.getSql(), CommandType.Text, dbCommand -> {
            sqlUpdateMate.getParameters().forEach(dbCommand::addParameter);
            dbCommand.executeNonQuery();
        });
    }

    @Transactional
    @Override
    public void wxQuestionnaireCommit(Questionnaire questionnaire) {
        LocalDateTime now = LocalDateTime.now();
        QuestionnaireAnswer answer;
        Object obj;
        for (QuestionnaireDetail detail : questionnaire.getDetailList()) {
            obj = detail.getValue();
            answer = new QuestionnaireAnswer();
            answer.setCreateTime(now);
            answer.setDbStatus(false);
            answer.setOpenid(questionnaire.getOpenid());
            answer.setQuestionnaireId(questionnaire.getId());
            answer.setDetailId(detail.getId());
            if (detail.getType() == 2) {
                List<String> result = new ArrayList<>();
                if (obj instanceof ArrayList<?>) {
                    for (Object o : (List<?>) obj) {
                        result.add((String) o);
                    }
                }
                answer.setValue(String.join(",", result));
            } else {
                answer.setValue(String.valueOf(obj));
            }
            questionnaireAnswerLogic.insert(UserRuntime.getSysUser().userId, answer);
        }
        WxScore wxScore = new WxScore();
        wxScore.setOpenid(questionnaire.getOpenid());
        wxScore.setNickname(questionnaire.getNickname());
        wxScore.setDbStatus(false);
        wxScore.setRewardType(2);
        wxScore.setRewardId(questionnaire.getId());
        wxScore.setRewardTitle(questionnaire.getName());
        wxScore.setScore(10);
        wxScoreLogic.insert(UserRuntime.getSysUser().userId, wxScore);
    }
}
